package com.platform.api;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.platform.annotation.LoginUser;
import com.platform.dto.CouponInfoVo;
import com.platform.entity.*;
import com.platform.service.*;
import com.platform.util.ApiBaseAction;
import com.platform.util.ApiPageUtils;
import com.platform.utils.CharUtil;
import com.platform.utils.Query;
import com.platform.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * API优惠券管理
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-03-23 15:31
 */
@Api(tags = "优惠券")
@RestController
@RequestMapping("/api/coupon")
public class ApiCouponController extends ApiBaseAction {
    @Autowired
    private ApiUserService apiUserService;
    @Autowired
    private ApiCouponService apiCouponService;
    @Autowired
    private ApiUserCouponService apiUserCouponService;
    @Autowired
    private ApiGoodsService apiGoodsService;
    @Autowired
    private ApiProductService apiProductService;
    @Autowired
    private ApiCartService apiCartService;


    //todo 购物车中可以使用的优惠券列表 难点系数较大，需要新增表记录


    //todo 每张优惠券能够使用的商品，应当再商品列表的接口中返回


    //todo 购物车中获取可用的优惠券

    /**
     * 根据购物车获取可用优惠券列表
     *
     * @param type 0-不可用；1-可用
     */
    @ApiOperation(value = "根据购物车获取可用优惠券列表")
    @PostMapping("/listByCart")
    public Object listByCart(@LoginUser UserVo loginUser,
                             @RequestParam(value = "type", defaultValue = "1") Integer type,
                             @RequestParam(value = "page", defaultValue = "1") Integer page,
                             @RequestParam(value = "size", defaultValue = "10") Integer size) {
        BigDecimal goodsTotalPrice = new BigDecimal(0.00);

        Map<String, Object> param = new HashMap<>();
        param.put("user_id", loginUser.getUserId());
        List<CartVo> cartList = apiCartService.queryList(param);

        //获取购物车统计信息
        for (CartVo cartItem : cartList) {
            if (null != cartItem.getChecked() && 1 == cartItem.getChecked()) {
                Integer goods_id = cartItem.getGoods_id();
                GoodsVo goodsVo = apiGoodsService.queryObject(goods_id);
                if (goodsVo.getIs_full_reduction() == 0 && goodsVo.getIs_rebate() == 0 && goodsVo.getIs_second_half_price() == 0) {
                    goodsTotalPrice = goodsTotalPrice.add(cartItem.getRetail_price().multiply(new BigDecimal(cartItem.getNumber())));
                }
            }
        }

        // 获取可用优惠券
        param.put("is_used", 0);
        param.put("page", page);
        param.put("limit", size);
        param.put("sidx", "id");
        param.put("order", "desc");
        param.put("goods_amount", goodsTotalPrice);
        param.put("enable", 1);

        if (type == 0) {
            param.put("enable", 0);
        }

        Query query = new Query(param);


        List<CouponVo> couponVos = apiCouponService.queryUserCoupons(query);

        for (CouponVo couponVo : couponVos) {
            // 可用优惠券
            if (goodsTotalPrice.compareTo(couponVo.getMin_goods_amount()) >= 0) {
                couponVo.setEnabled(1);
            } else {
                couponVo.setEnabled(0);
            }
        }

        int total = apiCouponService.queryUserCouponsTotal(query);

        return toResponsSuccess(new ApiPageUtils(couponVos, total, query.getLimit(), query.getPage()));

    }


    /**
     * 分页获取当前用户可以领取的优惠券列表
     *
     * @param loginUser
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("/listForGood")
    public Object listForGood(@LoginUser UserVo loginUser,
//                              @RequestParam(value = "goodsId") Integer goodsId,
                              @RequestParam(value = "page", defaultValue = "1") Integer page,
                              @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Long userId = loginUser.getUserId();

        //todo 在商品详情中显示优惠券列表
        Map<String, Object> params = new HashMap<>();
//        params.put("goods_id", goodsId);
        //发放方式 0：按订单发放 1：按用户发放 2:商品转发送券 3：按商品发放 4:新用户注册 5：线下发放 6评价好评红包（固定或随机红包） 7包邮
        Integer[] send_types = new Integer[]{0, 4};
        params.put("send_types", send_types);
        params.put("page", page);
        params.put("limit", size);
        params.put("sidx", "id");
        params.put("order", "asc");
        Query query = new Query(params);

        List<CouponVo> couponVos = apiCouponService.queryList(query);
        if (couponVos.size() > 0) {
            for (CouponVo couponVo : couponVos) {
                //todo 查询是否已经领取
                Map<String, Object> param = new HashMap<>();
                param.put("coupon_id", couponVo.getId());
                param.put("user_id", userId);
                param.put("is_used", 0);//是否已经使用：1-是；0-否
                int i = apiUserCouponService.queryTotal(param);
                if (i > 0) {
                    couponVo.setIsReceive(1);
                }
            }
        }
        int total = apiCouponService.queryTotal(query);
        ApiPageUtils pageUtil = new ApiPageUtils(couponVos, total, query.getLimit(), query.getPage());

        return toResponsSuccess(pageUtil);
    }

    /**
     * 领取优惠券
     *
     * @param loginUser
     * @param couponId
     * @return
     */
    @ApiOperation(value = "领取优惠券")
    @RequestMapping("/addUserCoupon")
    public Object addUserCoupon(@LoginUser UserVo loginUser, @RequestParam(value = "couponId") Integer couponId) {

        Long userId = loginUser.getUserId();

        //todo 判空
        CouponVo couponVo = apiCouponService.queryObject(couponId);
        if (couponVo == null) {
            return toResponsFail("不存在该优惠券");
        }

        //todo 判断是否已经过了领取时间
        boolean expired = DateUtil.isExpired(new Date(), DateField.SECOND, 0, couponVo.getSend_end_date());
        if (expired) {
            return toResponsFail("已超过优惠券领取时间");
        }

        //todo 判断是否已经领取过，并且是未使用的
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", userId);
        params.put("coupon_id", couponId);
        params.put("is_used", 0);
        int i = apiUserCouponService.queryTotal(params);
        if (i > 0) {
            return toResponsFail("您已经领取过了");
        }

        //todo 保存
        UserCouponVo userCouponVo = new UserCouponVo();
        userCouponVo.setAdd_time(new Date());
        userCouponVo.setCoupon_id(couponId);
        userCouponVo.setCoupon_number(CharUtil.getRandomString(12));
        userCouponVo.setUser_id(userId);
        userCouponVo.setIs_used(0);//是否已经使用：1-是；0-否
        apiUserCouponService.save(userCouponVo);

        return toResponsSuccess("");
    }


    /**
     * 分页获取用户优惠券列表
     *
     * @param loginUser
     * @param page
     * @param size
     * @param type      0-未使用，1-使用记录，2-已过期
     * @return
     */
    @ApiOperation(value = "分页获取用户优惠券列表")
    @RequestMapping("/listForUser")
    public Object listForUser(@LoginUser UserVo loginUser,
                              @RequestParam(value = "page", defaultValue = "1") Integer page,
                              @RequestParam(value = "size", defaultValue = "10") Integer size,
                              @RequestParam(value = "type", defaultValue = "0") Integer type) {
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", loginUser.getUserId());
        params.put("page", page);
        params.put("limit", size);
        params.put("sidx", "add_time");
        params.put("order", "desc");

        //todo 分页获取个人的优惠券列表（未使用，使用记录，已过期）
        if (type == 0) {//未使用
            params.put("is_used", 0);//是否已经使用：1-是；0-否
        } else if (type == 1) {//使用记录
            params.put("is_used", 1);//是否已经使用：1-是；0-否
        } else if (type == 2) {//已过期
            params.put("is_used", 0);
            params.put("is_expire", 1);
        } else {
            return toResponsFail("不存在该类型值");
        }

        Query query = new Query(params);
        List<UserCouponVo> userCouponVos = apiUserCouponService.queryList(query);
        if (userCouponVos.size() > 0) {
            for (UserCouponVo userCouponVo : userCouponVos) {
                Integer coupon_id = userCouponVo.getCoupon_id();
                userCouponVo.setCouponInfo(apiCouponService.queryObject(coupon_id));
            }
        }
        int total = apiUserCouponService.queryTotal(query);

        ApiPageUtils pageUtil = new ApiPageUtils(userCouponVos, total, query.getLimit(), query.getPage());

        return toResponsSuccess(pageUtil);
    }


    /**
     * 兑换优惠券
     */
    @RequestMapping("exchange")
    public Object exchange(@LoginUser UserVo loginUser, @RequestParam("couponNumber") String couponNumber) {

        Map<String, Object> param = new HashMap<>();
        param.put("coupon_number", couponNumber);
        List<UserCouponVo> couponVos = apiUserCouponService.queryList(param);
        if (null == couponVos || couponVos.size() == 0) {
            return toResponsFail("当前优惠码无效");
        }
        UserCouponVo userCouponVo = couponVos.get(0);
        if (null != userCouponVo.getUser_id() && !userCouponVo.getUser_id().equals(0L)) {
            return toResponsFail("当前优惠码已经兑换");
        }

        CouponVo couponVo = apiCouponService.queryObject(userCouponVo.getCoupon_id());
        if (null == couponVo || null == couponVo.getUse_end_date() || couponVo.getUse_end_date().before(new Date())) {
            return toResponsFail("当前优惠码已经过期");
        }
        userCouponVo.setUser_id(loginUser.getUserId());
        userCouponVo.setAdd_time(new Date());
        apiUserCouponService.update(userCouponVo);
        return toResponsSuccess(userCouponVo);
    }

    /**
     * 　　新用户领券
     */
    @RequestMapping("newuser")
    public Object newuser(@LoginUser UserVo loginUser) {

        // 是否领取过了
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", loginUser.getUserId());
        params.put("send_type", 4);
        List<CouponVo> couponVos = apiCouponService.queryUserCoupons(params);
        if (null != couponVos && couponVos.size() > 0) {
            return toResponsFail("已经领取过，不能重复领取");
        }
        // 领取
        Map<String, Object> couponParam = new HashMap<>();
        couponParam.put("send_type", 4);
        CouponVo newCouponConfig = apiCouponService.queryMaxUserEnableCoupon(couponParam);
        if (null != newCouponConfig) {
            UserCouponVo userCouponVo = new UserCouponVo();
            userCouponVo.setAdd_time(new Date());
            userCouponVo.setCoupon_id(newCouponConfig.getId());
            userCouponVo.setCoupon_number(CharUtil.getRandomString(12));
            userCouponVo.setUser_id(loginUser.getUserId());
            userCouponVo.setIs_used(0);//是否已经使用：1-是；0-否
            apiUserCouponService.save(userCouponVo);
            return toResponsSuccess(userCouponVo);
        } else {
            return toResponsFail("领取失败");
        }
    }

    /**
     * 　　转发领取红包
     */
    @RequestMapping("transActivit")
    public Object transActivit(@LoginUser UserVo loginUser, String sourceKey, Long referrer) {
        // 是否领取过了
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", loginUser.getUserId());
        params.put("send_type", 2);
        params.put("source_key", sourceKey);
        List<CouponVo> couponVos = apiCouponService.queryUserCoupons(params);
        if (null != couponVos && couponVos.size() > 0) {
            return toResponsObject(2, "已经领取过", couponVos);
        }
        // 领取
        Map<String, Object> couponParam = new HashMap<>();
        couponParam.put("send_type", 2);
        CouponVo newCouponConfig = apiCouponService.queryMaxUserEnableCoupon(couponParam);
        if (null != newCouponConfig) {
            UserCouponVo userCouponVo = new UserCouponVo();
            userCouponVo.setAdd_time(new Date());
            userCouponVo.setCoupon_id(newCouponConfig.getId());
            userCouponVo.setCoupon_number(CharUtil.getRandomString(12));
            userCouponVo.setUser_id(loginUser.getUserId());
            userCouponVo.setSource_key(sourceKey);
            userCouponVo.setReferrer(referrer);
            apiUserCouponService.save(userCouponVo);
            //
//            List<UserCouponVo> userCouponVos = new ArrayList<>();
//            userCouponVos.add(userCouponVo);
            //
            params = new HashMap<>();
            params.put("user_id", loginUser.getUserId());
            params.put("send_type", 2);
            params.put("source_key", sourceKey);
            couponVos = apiCouponService.queryUserCoupons(params);
            return toResponsSuccess(couponVos);
        } else {
            return toResponsFail("领取失败");
        }
    }
}
